package com.guigu.serviceorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guigu.common_util.pojo.IdWorker.IdWorker;
import com.guigu.common_util.pojo.utils.Result;
import com.guigu.serviceorder.entity.*;
import com.guigu.serviceorder.mapper.TbOrderConfigMapper;
import com.guigu.serviceorder.mapper.TbOrderItemMapper;
import com.guigu.serviceorder.mapper.TbOrderLogMapper;
import com.guigu.serviceorder.mapper.TbOrderMapper;
import com.guigu.serviceorder.service.CartService;
import com.guigu.serviceorder.service.GoodsService;
import com.guigu.serviceorder.service.ITbOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jobob
 * @since 2020-07-08
 */
@Service
public class TbOrderServiceImpl extends ServiceImpl<TbOrderMapper, TbOrder> implements ITbOrderService {

    @Autowired
    private TbOrderMapper tbOrderMapper;

    @Autowired
    private TbOrderItemMapper tbOrderItemMapper;

    @Autowired
    private TbOrderLogMapper tbOrderLogMapper;

    @Autowired
    private TbOrderConfigMapper tbOrderConfigMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private com.guigu.common_util.pojo.IdWorker.IdWorker idWorker11;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    //分页
    @Override
    public Result findPage(Map<String, Object> searchMap, Integer page, Integer size) {

        QueryWrapper<TbOrder> wrapper = createExample(searchMap);
        //创建page对象
        Page<TbOrder> pageTbOrder= new Page<>(page,size);
        baseMapper.selectPage(pageTbOrder,wrapper);
        if (pageTbOrder.getRecords() == null && pageTbOrder.getTotal() == 0){
            return Result.error();
        }
        return Result.ok().data("rows",pageTbOrder.getRecords()).data("total",pageTbOrder.getTotal());
    }
    //批量发货
    @Override
    public Result batchSend(List<TbOrder> orders) {
        //判断运单号和物流公司是否为空
        for (TbOrder order : orders) {
            if (order.getShippingCode() == null || order.getShippingName() == null) {
                throw new RuntimeException("请选择快递公司和填写快递单号");
            }
        }
        int row =0;
        //循环订
        for (TbOrder order : orders) {
            order.setOrderStatus("2");//订单状态 已发货
            order.setConsignStatus("2"); //发货状态 已发货
            order.setConsignTime(new Date());//发货时间
            row = row+tbOrderMapper.updateById(order);
            //记录订单日志
            TbOrderLog tbOrderLog =new TbOrderLog();
            tbOrderLog.setId(String.valueOf(new IdWorker().nextId()));
            tbOrderLog.setOperater(order.getUsername());
            tbOrderLog.setOrderId(order.getId());
            tbOrderLog.setOrderStatus(order.getOrderStatus());
            tbOrderLog.setPayStatus(order.getPayStatus());
            tbOrderLog.setRemarks("批量发货");
            tbOrderLog.setConsignStatus(order.getConsignStatus());
        }
        if(row>0)
            return Result.ok();
        return Result.error();
    }
    //合并
    @Override
    public Result merge(String orderId1, String orderId2) {
        //订单表的信息表的转移
        TbOrder tbOrder1 =this.tbOrderMapper.selectById(orderId1);
        TbOrder tbOrder2= this.tbOrderMapper.selectById(orderId2);
        if(tbOrder1.getTotalNum() == null){
            tbOrder1.setTotalNum(0);
        }
        if(tbOrder2.getTotalNum() == null){
            tbOrder2.setTotalNum(0);
        }
        if(tbOrder1.getPayMoney() == null){
            tbOrder1.setPayMoney(0);
        }
        if(tbOrder2.getPayMoney() == null){
            tbOrder2.setPayMoney(0);
        }
        tbOrder1.setTotalNum(tbOrder1.getTotalNum()+tbOrder2.getTotalNum());
        tbOrder1.setPreMoney(tbOrder1.getPayMoney()+tbOrder2.getPayMoney());
        tbOrder1.setUpdateTime(new Date());
        //修改
        tbOrder2.setIsDelete("1");
        tbOrder2.setUpdateTime(new Date());
        this.tbOrderMapper.updateById(tbOrder1);
        int row=this.tbOrderMapper.updateById(tbOrder2);
        //记录订单tbOrder1的日志记录
        TbOrderLog tbOrderLog =new TbOrderLog();
        tbOrderLog.setId(String.valueOf(new IdWorker().nextId()));
        tbOrderLog.setOperater(tbOrder1.getUsername());
        tbOrderLog.setOperateTime(new Date());
        tbOrderLog.setOrderStatus(tbOrder1.getOrderStatus());
        tbOrderLog.setPayStatus(tbOrder1.getPayStatus());
        tbOrderLog.setConsignStatus(tbOrder1.getConsignStatus());
        tbOrderLog.setRemarks("订单主表合并");
        tbOrderLog.setOrderId(tbOrder1.getId());
        this.tbOrderLogMapper.insert(tbOrderLog);
        //记录订单tbOrder2的日志记录
        TbOrderLog tbOrderLog2 =new TbOrderLog();
        tbOrderLog2.setId(String.valueOf(new IdWorker().nextId()));
        tbOrderLog2.setOperater(tbOrder2.getUsername());
        tbOrderLog2.setOperateTime(new Date());
        tbOrderLog2.setOrderStatus(tbOrder2.getOrderStatus());
        tbOrderLog2.setPayStatus(tbOrder2.getPayStatus());
        tbOrderLog2.setConsignStatus(tbOrder2.getConsignStatus());
        tbOrderLog2.setRemarks("订单从表合并");
        tbOrderLog2.setOrderId(tbOrder2.getId());
        this.tbOrderLogMapper.insert(tbOrderLog2);

        QueryWrapper<TbOrderItem> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("order_id",orderId2);
        List<TbOrderItem> list =this.tbOrderItemMapper.selectList(queryWrapper);
        Iterator<TbOrderItem> tbOrderItemIterator =list.iterator();
        while(tbOrderItemIterator.hasNext()) {
            this.tbOrderItemMapper.updateById(tbOrderItemIterator.next().setOrderId(orderId1));
        }
//        tbOrderItem.setOrderId(orderId1);
        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public Result split(List<TbSplitUtil> list) {
        // list 相- 修改源数据

        //创建迭代器
//        Iterator<TbSplitUtil> iterator = list.iterator();
//        int row=0;
//        while (iterator.hasNext()) {
//            row++;
          //  if(iterator.next().getSplitNum()!=0 || iterator.next().getSplitNum() !=iterator.next().getTbOrderItem().getNum() || iterator.next().getSplitNum()!=null){
//                TbSplitUtil nexts = iterator.next();
//                // 获取需要拆分的数据
//                TbOrderItem tbOrderItem = nexts.getTbOrderItem();
//                Integer oldnum = tbOrderItem.getNum();
//
//                // 需要拆分的数量
//                Integer splitNum = nexts.getSplitNum();
//                Integer newNum = oldnum - splitNum;
//
//                // 修改数据
//                tbOrderItem.setNum(newNum);
//
//                row = this.tbOrderItemMapper.updateById(tbOrderItem);
//                IdWorker idWorker=new IdWorker();
//                // 新增拆分列
//                tbOrderItem.setNum(splitNum);
//                tbOrderItem.setId(String.valueOf(idWorker.nextId()+""));
                //this.tbOrderItemMapper.insert(tbOrderItem);
          //  }
//        }
//        System.out.println(row);
//        int num =0;
//        for(int i=1;i<list.size();i++){
//            num = num + list.get(i).getTbOrderItem().getNum();
//            TbOrderItem tbOrderItem1 =new TbOrderItem();
//            tbOrderItem1.setNum(Integer.parseInt(list.get(i).getSplitNum()));
//            this.tbOrderItemMapper.insert(tbOrderItem1);
//        }
//        TbOrderItem tbOrderItem =new TbOrderItem();
//        tbOrderItem.setNum(tbOrderItem.getNum()-num);
//        this.tbOrderItemMapper.updateById(tbOrderItem);
        int row =0;
        for (int i = 0;i<list.size();i++){
            if(list.get(i).getSplitNum()<0 || list.get(i).getSplitNum()>list.get(i).getTbOrderItem().getNum()) {
                return Result.error();
            } else if(list.get(i).getSplitNum()!=0 || list.get(i).getSplitNum()!=list.get(i).getTbOrderItem().getNum() || list.get(i).getSplitNum() != null){
                //获取需要拆分的数据
                TbOrderItem tbOrderItem = list.get(i).getTbOrderItem();
                Integer oldnum = tbOrderItem.getNum();

                //需要拆分的数量
                Integer splitNum = list.get(i).getSplitNum();
                //拆分出来的数量
                Integer newNum = oldnum - splitNum;

                //修改数据
                tbOrderItem.setNum(newNum);

                row = this.tbOrderItemMapper.updateById(tbOrderItem);
                IdWorker idWorker=new IdWorker();
                // 新增拆分列
                tbOrderItem.setNum(splitNum);
                tbOrderItem.setId(idWorker.nextId()+"");
                this.tbOrderItemMapper.insert(tbOrderItem);
            }
        }

        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public TbOrderItem findByOrderId(String OrderId) {
        QueryWrapper<TbOrderItem> wrapper=new QueryWrapper<>();
        wrapper.eq("order_id",OrderId);
        return this.tbOrderItemMapper.selectOne(wrapper);
    }

    @Override
    public Result closeOrder(List<TbOrder> orders) {
        //order中是否有订单状态不为0
//        for (TbOrder order : orders) {
//            if (order.getOrderStatus() !="0" ) {
//                throw new RuntimeException("只能关闭待付款的订单");
//            }
//        }
        System.out.println(orders);
        int row =0;
        //循环orders将状态从0改成4
        for (TbOrder order : orders) {
            order.setOrderStatus("4");//订单状态 已发货
            row = row+tbOrderMapper.updateById(order);
            //记录订单日志
            TbOrderLog tbOrderLog =new TbOrderLog();
            tbOrderLog.setId(String.valueOf(new IdWorker().nextId()));
            tbOrderLog.setOperater(order.getUsername());
            tbOrderLog.setOperateTime(new Date());
            tbOrderLog.setOrderStatus(order.getOrderStatus());
            tbOrderLog.setPayStatus(order.getPayStatus());
            tbOrderLog.setConsignStatus(order.getConsignStatus());
            tbOrderLog.setRemarks("订单状态修改");
            tbOrderLog.setOrderId(order.getId());
            this.tbOrderLogMapper.insert(tbOrderLog);

            //日志
            TbOrderLog tbOrderLog1 =new TbOrderLog();
            tbOrderLog1.setId(String.valueOf(new IdWorker().nextId()));
            tbOrderLog1.setOperater(order.getUsername());
            tbOrderLog1.setOperateTime(new Date());
            tbOrderLog1.setOrderStatus(order.getOrderStatus());
            tbOrderLog1.setPayStatus(order.getPayStatus());
            tbOrderLog1.setConsignStatus(order.getConsignStatus());
            tbOrderLog1.setRemarks("订单关闭");
            tbOrderLog1.setOrderId(order.getId());
            this.tbOrderLogMapper.insert(tbOrderLog1);
        }
        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public Result deleteOrder(List<TbOrder> orders) {
        //order中是否有订单状态不为4
//        for (TbOrder order : orders) {
//            if (order.getOrderStatus() !="4" ) {
//                throw new RuntimeException("只能关闭待付款的订单");
//            }
//        }
        //循环orders将是4的删除
        int row =0;
        for (TbOrder order : orders) {
            order.setIsDelete("1");
            row =row+tbOrderMapper.updateById(order);
            //记录订单日志
            TbOrderLog tbOrderLog =new TbOrderLog();
            tbOrderLog.setId(String.valueOf(new IdWorker().nextId()));
            tbOrderLog.setOperater(order.getUsername());
            tbOrderLog.setOperateTime(new Date());
            tbOrderLog.setOrderStatus(order.getOrderStatus());
            tbOrderLog.setPayStatus(order.getPayStatus());
            tbOrderLog.setConsignStatus(order.getConsignStatus());
            tbOrderLog.setRemarks("订单删除");
            tbOrderLog.setOrderId(order.getId());
            this.tbOrderLogMapper.insert(tbOrderLog);
        }
        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public Map selectOrderAndOrderItem(String orderId) {

        List<TbOrderItem> tbOrderItem = this.tbOrderItemMapper.selectList(
                new QueryWrapper<TbOrderItem>()
                        .eq("order_id", orderId)
        );
        Map map = new HashMap();
        map.put("tbOrderItem", tbOrderItem);
        return map;
    }

    @Override
    public Result closeOrderOne(String orderId) {
        TbOrder tbOrder = this.tbOrderMapper.selectById(orderId);
        tbOrder.setOrderStatus("4");
        int row = this.tbOrderMapper.updateById(tbOrder);
        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public Result deleteOrderOne(String orderId) {
        TbOrder tbOrder = this.tbOrderMapper.selectById(orderId);
        tbOrder.setIsDelete("1");
        int row = this.tbOrderMapper.updateById(tbOrder);
        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public Result confirmReceiptOne(String orderId) {
        TbOrder tbOrder = this.tbOrderMapper.selectById(orderId);
        tbOrder.setOrderStatus("3");
        int row = this.tbOrderMapper.updateById(tbOrder);
        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public Result confirmReceipt(List<TbOrder> orders) {
        int row =0;
        for (TbOrder order : orders) {
            order.setOrderStatus("3");
            row =row+tbOrderMapper.updateById(order);
        }
        if(row>0)
            return Result.ok();
        return Result.error();
    }

    @Override
    public Map<String, Object> add(TbOrder order) {
        // 获取购物车（刷新表单）
        List<Map<String, Object>> orderItemList = cartService.findNewOrderItemList(order.getUsername());
        // 获取选中的购物车
        List<TbOrderItem> orderItems = orderItemList.stream().filter(cart -> (boolean) cart.get("checked")).map(cart -> (TbOrderItem) cart.get("item")).collect(Collectors.toList());
        // 扣减库存
        if(!goodsService.deductionStock(orderItems)){
            throw new RuntimeException("库存扣减失败");
        }

        try {
            // 保订单主表
            order.setId(idWorker11.nextId()+"");
            // 和合计数计算
            IntStream numStream =
                    orderItems.stream().mapToInt(TbOrderItem::getNum);
            IntStream moneyStream =
                    orderItems.stream().mapToInt(TbOrderItem::getMoney);
            int totalNum=numStream.sum();//总数量
            int totalMoney=moneyStream.sum();//订单总金额
            int preMoney = cartService.preferential(order.getUsername()); //计算优惠金额
            order.setTotalNum(totalNum);//总数量
            order.setTotalMoney(totalMoney);//总金额

            order.setPreMoney(preMoney);//优惠金额
            order.setPayMoney(totalMoney-preMoney);//支付金额=总金额+优惠金额
            order.setCreateTime(new Date());//订单创建日期
            order.setOrderStatus("0"); // 订单状态
            order.setPayStatus("0"); // 支付状态：未支付
            order.setConsignStatus("0"); //发货状态：未发货
            order.setIsDelete("0");
            baseMapper.insert(order);

            double proportion = (double)order.getPayMoney()/totalMoney;//保存订单明细
            for(TbOrderItem orderItem:orderItems){
                orderItem.setOrderId(order.getId());//订单主表ID
                orderItem.setId(idWorker11.nextId()+"");
                orderItem.setPayMoney( (int)(orderItem.getMoney()* proportion) );//支付金额
                tbOrderItemMapper.insert(orderItem);
            }
        } catch (Exception e) {
            rabbitTemplate.convertAndSend("","queue.skuback", JSON.toJSONString(orderItems));
            e.printStackTrace();
        }

        //清除选中的购物车
        cartService.deleteCheckedCart(order.getUsername());
        //返回订单号和支付的金额
        Map<String, Object> map=new HashMap();
        map.put("ordersn", order.getId() );
        map.put("money",order.getPayMoney());
        return map;
    }

    /**
     * 修改订单状态
     * @param orderId
     * @param transactionId
     */
    @Override
    public void updatePayStatus(String orderId, String transactionId) {
        TbOrder order = baseMapper.selectById(orderId);
        if(order!=null && "0".equals(order.getPayStatus())) { //存在订单且状态为0
            order.setPayStatus("1");
            order.setOrderStatus("1");
            order.setUpdateTime(new Date());
            order.setPayTime(new Date());
            order.setTransactionId(transactionId);//微信返回的交易流水号
            baseMapper.updateById(order);
            //记录订单变动日志
            TbOrderLog orderLog = new TbOrderLog();
            orderLog.setId(idWorker11.nextId()+"");
            orderLog.setOperater("system");// 系统
            orderLog.setOperateTime(new Date());//当前日期
            orderLog.setOrderStatus("1");
            orderLog.setPayStatus("1");
            orderLog.setRemarks("支付流水号" + transactionId);
            orderLog.setOrderId(order.getId());
            tbOrderLogMapper.insert(orderLog);
        }
    }

    // 根据查询条件封装模块对象
    private QueryWrapper<TbOrder> createExample(Map<String, Object> searchMap) {
        QueryWrapper<TbOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete","0");
        if(searchMap!=null) {
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id")))
                wrapper.eq("id",searchMap.get("id"));
            if(searchMap.get("receiverContact") != null && !"".equals(searchMap.get("")))
                wrapper.eq("receiver_contack",searchMap.get("receiverContack"));
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus")))
                wrapper.eq("order_status",searchMap.get("orderStatus"));
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType")))
                wrapper.eq("source_type",searchMap.get("sourceType"));
            if(searchMap.get("createTime")!=null && !"".equals(searchMap.get("createTime")))
                wrapper.eq("create_time",searchMap.get("createTime"));
        }
        return wrapper;
    }

}
